import pygame
import random
import sys

# 初始化pygame
pygame.init()

# 设置中文字体
pygame.font.init()
try:
    # 尝试加载系统中的中文字体
    font = pygame.font.SysFont(["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 30)
    small_font = pygame.font.SysFont(["SimHei", "WenQuanYi Micro Hei", "Heiti TC"], 24)
except:
    # 如果找不到中文字体，使用默认字体
    font = pygame.font.Font(None, 30)
    small_font = pygame.font.Font(None, 24)

# 游戏常量设置
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
GRID_SIZE = 8  # 8x8网格
CELL_SIZE = 60
PADDING = 20
GRID_WIDTH = GRID_SIZE * CELL_SIZE
GRID_HEIGHT = GRID_SIZE * CELL_SIZE
GRID_X = (SCREEN_WIDTH - GRID_WIDTH) // 2
GRID_Y = (SCREEN_HEIGHT - GRID_HEIGHT) // 2

# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GRAY = (200, 200, 200)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
PURPLE = (128, 0, 128)
ORANGE = (255, 165, 0)
CYAN = (0, 255, 255)

# 方块颜色列表
COLORS = [RED, GREEN, BLUE, YELLOW, PURPLE, ORANGE, CYAN]

# 创建屏幕
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("消消乐")

# 游戏类
class MatchThreeGame:
    def __init__(self):
        self.grid = []
        self.selected_cell = None
        self.score = 0
        self.moves = 0
        self.max_moves = 30
        self.game_over = False
        self.initialize_grid()
    
    def initialize_grid(self):
        """初始化游戏网格，确保没有初始的三个相连"""
        self.grid = [[0 for _ in range(GRID_SIZE)] for _ in range(GRID_SIZE)]
        
        for row in range(GRID_SIZE):
            for col in range(GRID_SIZE):
                # 生成一个颜色，但确保不会形成三个相连
                while True:
                    color_idx = random.randint(0, len(COLORS) - 1)
                    # 检查水平方向
                    if col >= 2 and self.grid[row][col-1] == color_idx and self.grid[row][col-2] == color_idx:
                        continue
                    # 检查垂直方向
                    if row >= 2 and self.grid[row-1][col] == color_idx and self.grid[row-2][col] == color_idx:
                        continue
                    self.grid[row][col] = color_idx
                    break
    
    def draw(self):
        """绘制游戏界面"""
        screen.fill(GRAY)
        
        # 绘制网格
        for row in range(GRID_SIZE):
            for col in range(GRID_SIZE):
                # 计算方块位置
                x = GRID_X + col * CELL_SIZE
                y = GRID_Y + row * CELL_SIZE
                
                # 绘制方块
                color_idx = self.grid[row][col]
                pygame.draw.rect(screen, COLORS[color_idx], (x + 2, y + 2, CELL_SIZE - 4, CELL_SIZE - 4))
                
                # 绘制边框
                if self.selected_cell == (row, col):
                    pygame.draw.rect(screen, BLACK, (x, y, CELL_SIZE, CELL_SIZE), 3)
                else:
                    pygame.draw.rect(screen, WHITE, (x, y, CELL_SIZE, CELL_SIZE), 1)
        
        # 绘制分数和步数
        score_text = font.render(f"分数: {self.score}", True, BLACK)
        screen.blit(score_text, (PADDING, PADDING))
        
        moves_text = font.render(f"步数: {self.moves}/{self.max_moves}", True, BLACK)
        screen.blit(moves_text, (PADDING, PADDING + 40))
        
        # 游戏结束时显示信息
        if self.game_over:
            # 半透明背景
            overlay = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT), pygame.SRCALPHA)
            overlay.fill((0, 0, 0, 128))
            screen.blit(overlay, (0, 0))
            
            result_text = font.render("游戏结束!", True, WHITE)
            score_final_text = font.render(f"最终分数: {self.score}", True, WHITE)
            restart_text = small_font.render("按 R 键重新开始", True, WHITE)
            
            screen.blit(result_text, (SCREEN_WIDTH // 2 - result_text.get_width() // 2, SCREEN_HEIGHT // 2 - 50))
            screen.blit(score_final_text, (SCREEN_WIDTH // 2 - score_final_text.get_width() // 2, SCREEN_HEIGHT // 2))
            screen.blit(restart_text, (SCREEN_WIDTH // 2 - restart_text.get_width() // 2, SCREEN_HEIGHT // 2 + 50))
        
        pygame.display.flip()
    
    def select_cell(self, pos):
        """选择一个方块"""
        x, y = pos
        
        # 检查点击是否在网格内
        if GRID_X <= x <= GRID_X + GRID_WIDTH and GRID_Y <= y <= GRID_Y + GRID_HEIGHT:
            # 计算点击的是哪个格子
            col = (x - GRID_X) // CELL_SIZE
            row = (y - GRID_Y) // CELL_SIZE
            
            # 如果没有选中任何格子，直接选中
            if self.selected_cell is None:
                self.selected_cell = (row, col)
            # 如果选中的是同一个格子，取消选中
            elif self.selected_cell == (row, col):
                self.selected_cell = None
            # 检查是否相邻
            elif self.is_adjacent(self.selected_cell, (row, col)):
                # 尝试交换并检查是否有匹配
                if self.try_swap(self.selected_cell, (row, col)):
                    self.moves += 1
                    # 检查是否达到最大步数
                    if self.moves >= self.max_moves:
                        self.game_over = True
                self.selected_cell = None
            # 如果不是相邻的，重新选择
            else:
                self.selected_cell = (row, col)
    
    def is_adjacent(self, cell1, cell2):
        """检查两个格子是否相邻"""
        row1, col1 = cell1
        row2, col2 = cell2
        
        # 相邻定义为水平或垂直相邻
        return (abs(row1 - row2) == 1 and col1 == col2) or (abs(col1 - col2) == 1 and row1 == row2)
    
    def try_swap(self, cell1, cell2):
        """尝试交换两个格子，并检查是否有匹配"""
        row1, col1 = cell1
        row2, col2 = cell2
        
        # 交换格子
        self.grid[row1][col1], self.grid[row2][col2] = self.grid[row2][col2], self.grid[row1][col1]
        
        # 检查是否有匹配
        matches = self.find_matches()
        
        if matches:
            # 有匹配，处理匹配
            self.process_matches(matches)
            return True
        else:
            # 没有匹配，交换回来
            self.grid[row1][col1], self.grid[row2][col2] = self.grid[row2][col2], self.grid[row1][col1]
            return False
    
    def find_matches(self):
        """查找所有匹配的三个或更多相同颜色的方块"""
        matches = set()
        
        # 检查水平匹配
        for row in range(GRID_SIZE):
            col = 0
            while col < GRID_SIZE - 2:
                if (self.grid[row][col] == self.grid[row][col+1] and 
                    self.grid[row][col] == self.grid[row][col+2]):
                    # 找到一个匹配的起始点，继续检查有多少个连续相同的
                    match_length = 3
                    while col + match_length < GRID_SIZE and self.grid[row][col] == self.grid[row][col+match_length]:
                        match_length += 1
                    
                    # 添加匹配的格子
                    for i in range(match_length):
                        matches.add((row, col + i))
                    
                    col += match_length
                else:
                    col += 1
        
        # 检查垂直匹配
        for col in range(GRID_SIZE):
            row = 0
            while row < GRID_SIZE - 2:
                if (self.grid[row][col] == self.grid[row+1][col] and 
                    self.grid[row][col] == self.grid[row+2][col]):
                    # 找到一个匹配的起始点，继续检查有多少个连续相同的
                    match_length = 3
                    while row + match_length < GRID_SIZE and self.grid[row][col] == self.grid[row+match_length][col]:
                        match_length += 1
                    
                    # 添加匹配的格子
                    for i in range(match_length):
                        matches.add((row + i, col))
                    
                    row += match_length
                else:
                    row += 1
        
        return matches
    
    def process_matches(self, matches):
        """处理匹配的方块，增加分数并移除方块"""
        # 增加分数
        self.score += len(matches) * 10
        
        # 移除匹配的方块
        for row, col in matches:
            self.grid[row][col] = None
        
        # 让方块下落
        self.drop_blocks()
        
        # 填充新方块
        self.fill_empty_cells()
        
        # 检查是否有新的匹配
        new_matches = self.find_matches()
        if new_matches:
            self.process_matches(new_matches)
    
    def drop_blocks(self):
        """让方块下落填补空白"""
        for col in range(GRID_SIZE):
            empty_count = 0
            # 从底部向上检查
            for row in range(GRID_SIZE - 1, -1, -1):
                if self.grid[row][col] is None:
                    empty_count += 1
                elif empty_count > 0:
                    # 将方块下移
                    self.grid[row + empty_count][col] = self.grid[row][col]
                    self.grid[row][col] = None
    
    def fill_empty_cells(self):
        """填充空白格子"""
        for col in range(GRID_SIZE):
            for row in range(GRID_SIZE):
                if self.grid[row][col] is None:
                    self.grid[row][col] = random.randint(0, len(COLORS) - 1)
    
    def reset(self):
        """重置游戏"""
        self.initialize_grid()
        self.selected_cell = None
        self.score = 0
        self.moves = 0
        self.game_over = False

# 主游戏循环
def main():
    clock = pygame.time.Clock()
    game = MatchThreeGame()
    
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.MOUSEBUTTONDOWN and not game.game_over:
                if event.button == 1:  # 左键点击
                    game.select_cell(pygame.mouse.get_pos())
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    game.reset()
        
        # 绘制游戏
        game.draw()
        
        clock.tick(60)
    
    pygame.quit()
    sys.exit()

if __name__ == "__main__":
    main()